import { createRouter, createWebHistory } from 'vue-router'
import { routeTree } from './routeTree'
import { useUserStoreWithOut } from '@/store/modules/user'
import { useNProgress } from '@/hooks/useNProgress'

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_APP_CONFIG_BASE ?? '/'),
  routes: routeTree,
})

const { start, done } = useNProgress()

const whiteList = ['/login', '/home', '/goods', '/my'] // 不重定向白名单

router.beforeEach(async (to, from, next) => {
  start()
  const userStore = useUserStoreWithOut()
  if (userStore.getUserInfo) {
    if (to.path === '/login') {
      next({ path: '/' })
    }
    else {
      next()
    }
  }
  else {
    if (whiteList.includes(to.path))
      next()
    else next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
  }
})

router.afterEach((to) => {
  done() // 结束Progress
})

export default router
